package com.hongyun.tms.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 转化工具类,如pojo转为Dto,或者list 转 dtoList
 *
 * @author liPeng
 * @date 2024-05-31
 */
@Slf4j
public class MapperingUtils {

    public static <T> List<T> copyList(List<? extends Object> poList, final Class<T> voClass) {
        List<T> voList = new ArrayList<T>();
        T voObj = null;
        for (Object poObj : poList) {
            try {
                voObj = voClass.newInstance();
                BeanUtils.copyProperties(poObj, voObj);
                voList.add(voObj);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return voList;
    }

    public static <T> T copyProperties(Object obj, final Class<T> voClass) {
        if (obj == null) {
            return null;
        } else {
            try {
                T t = voClass.newInstance();
                BeanUtils.copyProperties(obj, t);
                return t;
            } catch (Exception e) {
                log.error("对象转化失败:   " + obj.getClass().getName() + " 转" + voClass.getName());
                throw new RuntimeException(e);
            }
        }
    }

    public static Map<String, String> clazzToMap(Object obj) {
        Class<?> aClass = obj.getClass();
        Map<String, String> map = new HashMap<>();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            String methodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            try {
                Method method = aClass.getMethod("get" + methodName);
                Object invoke = method.invoke(obj);
                String value = invoke.toString();
                map.put(fieldName, value);
            } catch (Exception e) {
                //获取value失败，这里不做处理
            }
        }
        return map;
    }


}
